/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import model.Defectlog;
import model.Employee;
import model.Logstatus;
import model.Logtype;
import model.Priority;
import model.Project;
import model.Severity;
import session.DefectlogFacadeRemote;
import session.EmployeeFacadeRemote;
import session.LogstatusFacadeRemote;
import session.LogtypeFacadeRemote;
import session.PriorityFacadeRemote;
import session.ProjectFacadeRemote;
import session.SeverityFacadeRemote;
import util.Constants;

/**
 *
 * @author THAT_HIEN
 */
public class defectLogController {

    /**
     * Get Action Link HTML code to insert into JSP file.
     */
    public static String getActionLink(String id) {
        String edit = "<a onclick=\"doAction(frmIndex, '" + Constants.DEFECT_LOG_PAGE_NAME
                + "', '" + Constants.DEFECTLOG_EDIT + "', '" + Constants.UNDEFINED_PAGE_NAME
                + "' , '" + Constants.SHOW_EDIT_PAGE + "', '" + id + "')\">Edit</a>";
        String delete = "<a onclick=\"doAction(frmIndex, '" + Constants.DEFECT_LOG_PAGE_NAME
                + "', '" + Constants.DEFECTLOG_LIST + "', '" + Constants.UNDEFINED_PAGE_NAME
                + "' , '" + Constants.DELETE + "', '" + id + "')\">Delete</a>";

        return edit + delete;
    }

    public static void loadStatusData(JspWriter out) {
        Controller.log.info("loadStatusData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Logstatus> listLog = util.Facade.getLogStatusFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Logstatus a = listLog.get(i);
                out.println("<option value='" + a.getLogStatusID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadStatusData.");
        } catch (Exception ex) {
            Controller.log.error("Error loadStatusData: " + ex.getMessage());
        }
    }

    public static void loadStatusData(JspWriter out, String statusID) {
        if (statusID == null || statusID.isEmpty()) {
            loadStatusData(out);
        } else {
            Controller.log.info("loadStatusData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                List<model.Logstatus> listLog = util.Facade.getLogStatusFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Logstatus a = listLog.get(i);
                    if (!statusID.equals(a.getLogStatusID())) {
                        out.println("<option value='" + a.getLogStatusID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getLogStatusID()
                                + "' selected='selected'>" + a.getName() + "</option>");
                    }
                }
                Controller.log.info("loadStatusData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadStatusData: " + ex.getMessage());
            }
        }
    }

    public static void loadSeverityData(JspWriter out) {
        Controller.log.info("loadSeverityData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Severity> listLog = util.Facade.getSeverityFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Severity a = listLog.get(i);
                out.println("<option value='" + a.getSeverityID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadSeverityData Finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadSeverityData: " + ex.getMessage());
        }
    }

    public static void loadSeverityData(JspWriter out, String severityID) {
        if (severityID == null || severityID.isEmpty()) {
            loadSeverityData(out);
        } else {
            Controller.log.info("loadSeverityData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                List<model.Severity> listLog = util.Facade.getSeverityFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Severity a = listLog.get(i);
                    if (!severityID.equals(a.getSeverityID())) {
                        out.println("<option value='" + a.getSeverityID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getSeverityID()
                                + "' selected='selected'>" + a.getName() + "</option>");
                    }
                }
                Controller.log.info("End loadSeverityData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadSeverityData: " + ex.getMessage());
            }
        }
    }

    public static void loadProjectData(JspWriter out) {
        Controller.log.info("loadProjectData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Project> listLog = util.Facade.getProjectFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Project a = listLog.get(i);
                out.println("<option value='" + a.getProjectID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadProjectData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadProjectData: " + ex.getMessage());
        }
    }

    public static void loadProjectData(JspWriter out, String projectID) {
        if (projectID == null || projectID.isEmpty()) {
            loadProjectData(out);
        } else {
            Controller.log.info("loadProjectData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                List<model.Project> listLog = util.Facade.getProjectFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Project a = listLog.get(i);
                    if (!projectID.equals(a.getProjectID())) {
                        out.println("<option value='" + a.getProjectID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getProjectID()
                                + "' selected='selected'>" + a.getName() + "</option>");
                    }
                }
                Controller.log.info("End loadProjectData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadProjectData: " + ex.getMessage());
            }
        }
    }

    public static void loadPriorityData(JspWriter out) {
        Controller.log.info("loadPriorityData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Priority> listLog = util.Facade.getPriorityFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Priority a = listLog.get(i);
                out.println("<option value='" + a.getPriorityID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadPriorityData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadPriorityData: " + ex.getMessage());
        }
    }

    public static void loadPriorityData(JspWriter out, String priorityID) {
        if (priorityID == null || priorityID.isEmpty()) {
            loadPriorityData(out);
        } else {
            Controller.log.info("loadPriorityData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                List<model.Priority> listLog = util.Facade.getPriorityFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Priority a = listLog.get(i);
                    if (!priorityID.equals(a.getPriorityID())) {
                        out.println("<option value='" + a.getPriorityID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getPriorityID()
                                + "' selected='selected'>" + a.getName() + "</option>");
                    }
                }
                Controller.log.info("End loadPriorityData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadPriorityData: " + ex.getMessage());
            }
        }
    }

    public static void loadLogtypeData(JspWriter out) {
        Controller.log.info("loadLogtypeData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Logtype> listLog = util.Facade.getLogTypeFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Logtype a = listLog.get(i);
                out.println("<option value='" + a.getLogTypeID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadLogtypeData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadLogtypeData: " + ex.getMessage());
        }
    }

    public static void loadLogtypeData(JspWriter out, String logTypeID) {
        if (logTypeID == null || logTypeID.isEmpty()) {
            loadLogtypeData(out);
        } else {
            Controller.log.info("loadLogtypeData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                List<model.Logtype> listLog = util.Facade.getLogTypeFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Logtype a = listLog.get(i);
                    if (!logTypeID.equals(a.getLogTypeID())) {
                        out.println("<option value='" + a.getLogTypeID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getLogTypeID()
                                + "' selected='selected'>" + a.getName() + "</option>");
                    }
                }
                Controller.log.info("End loadLogtypeData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadLogtypeData: " + ex.getMessage());
            }
        }
    }

    public static void loadEmployeeData(JspWriter out) {
        Controller.log.info("loadEmployeeData");
        try {
            /*
             * Show Severity List on Screen
             */
            List<model.Employee> listLog = util.Facade.getEmployeeFacade().findAll();
            out.println("<option value='none'></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Employee a = listLog.get(i);
                out.println("<option value='" + a.getEmployeeID() + "'>" + a.getShortName() + "</option>");
            }
            Controller.log.info("loadEmployeeData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadEmployeeData: " + ex.getMessage());
        }
    }

    public static void loadEmployeeData(JspWriter out, String logTypeID) {
        if (logTypeID == null || logTypeID.isEmpty()) {
            loadEmployeeData(out);
        } else {
            Controller.log.info("loadEmployeeData");
            try {
                /*
                 * Show Severity List on Screen
                 */
                int id = Integer.parseInt(logTypeID);
                List<model.Employee> listLog = util.Facade.getEmployeeFacade().findAll();
                out.println("<option value='none'></option>");
                for (int i = 0; i < listLog.size(); i++) {
                    Employee a = listLog.get(i);
                    if (i != id) {
                        out.println("<option value='" + a.getEmployeeID() + "'>"
                                + a.getName() + "</option>");
                    } else {
                        out.println("<option value='" + a.getEmployeeID()
                                + "' selected='selected'>" + a.getShortName() + "</option>");
                    }
                }
                Controller.log.info("End loadEmployeeData.");
            } catch (Exception ex) {
                Controller.log.error("Error loadEmployeeData: " + ex.getMessage());
            }
        }
    }

    public static void showLogList(JspWriter out, List<Defectlog> list) {
        Controller.log.info("begin showLogList");
        try {
            //Create the title
            out.println("<div id='list-table'>");
            out.println("<div class='row'>");
            out.println("<div class='column-header' style='width: "
                    + Constants.ACTION_COLUMN_SIZE + ";'>Action</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Title</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_DESCRIPTION_COLUMN_SIZE + ";'>Description</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.DATE_COLUMN_SIZE + ";'>Created Date</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Status</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Product</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Severity</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Priority</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Type</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Defect By</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Assigned To</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.DATE_COLUMN_SIZE + ";'>Deadline</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_DESCRIPTION_COLUMN_SIZE + ";'>CorrectiveAction</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>Fixed By</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.DATE_COLUMN_SIZE + ";'>Fixed Date</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.DATE_COLUMN_SIZE + ";'>Closed Date</div>");
            out.println("<div class='column-header' style='width: "
                    + Constants.DATE_COLUMN_SIZE + ";'>Action</div>");
            out.println("<div class='clear'></div>");
            out.println("</div>");

            Logstatus status = null;
            Severity severity = null;
            Priority priority = null;
            Logtype type = null;
            Employee defectedBy = null, assignedTo = null, fixedBy = null;
            String personDefected = null, personAssigned = null, personFixed = null;
            String createdDate = null, deadline = null, fixedDate = null, closedDate = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

            //Show the contents.
            for (int i = 0; i < list.size(); i++) {
                Defectlog node = list.get(i);
                status = node.getStatusID();
                severity = node.getSeverityID();
                priority = node.getPriorityID();
                type = node.getLogTypeID();
                defectedBy = node.getDefectedBy();
                assignedTo = node.getAssignedTo();
                fixedBy = node.getFixedBy();

                if (defectedBy != null) {
                    personDefected = defectedBy.getName();
                } else {
                    personDefected = "";
                }
                if (assignedTo != null) {
                    personAssigned = assignedTo.getName();
                } else {
                    personAssigned = "";
                }
                if (fixedBy != null) {
                    personFixed = fixedBy.getName();
                } else {
                    personFixed = "";
                }
                if (node.getCreatedDate() == null) {
                    createdDate = "";
                } else {
                    createdDate = dateFormat.format(node.getCreatedDate());
                }
                if (node.getDeadline() == null) {
                    deadline = "";
                } else {
                    deadline = dateFormat.format(node.getDeadline());
                }
                if (node.getFixedDate() == null) {
                    fixedDate = "";
                } else {
                    fixedDate = dateFormat.format(node.getFixedDate());
                }
                if (node.getClosedDate() == null) {
                    closedDate = "";
                } else {
                    closedDate = dateFormat.format(node.getClosedDate());
                }


                out.println("<div class='row'>");
                out.println("<div class='column' style='width: "
                        + Constants.ACTION_COLUMN_SIZE + ";'>"
                        + getActionLink(node.getLogID().toString()) + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + node.getTitle() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_DESCRIPTION_COLUMN_SIZE + ";'>"
                        + node.getDescription() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.DATE_COLUMN_SIZE + ";'>"
                        + createdDate + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + status.getName() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + node.getProduct() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + severity.getName() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + priority.getName() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + type.getName() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + personDefected + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + personAssigned + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.DATE_COLUMN_SIZE + ";'>"
                        + deadline + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_DESCRIPTION_COLUMN_SIZE + ";'>"
                        + node.getCorrectiveAction() + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.OBJECT_NAME_COLUMN_SIZE + ";'>"
                        + personFixed + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.DATE_COLUMN_SIZE + ";'>"
                        + fixedDate + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.DATE_COLUMN_SIZE + ";'>"
                        + closedDate + "</div>");
                out.println("<div class='column' style='width: "
                        + Constants.ACTION_COLUMN_SIZE + ";'>"
                        + getActionLink(node.getLogID().toString()) + "</div>");
                out.println("<div class='clear'></div>");
                out.println("</div>");
            }
            out.print("</div>");
            Controller.log.info("End showLogList");
        } catch (Exception ex) {
            controller.Controller.log.error("Error showLogList: " + ex.getMessage());
        }
    }
    /**
     * Show all Logs exists in database.
     */
    public static void showAllLogs(JspWriter out) {
        try {
        Controller.log.info("showAllLogs");
            List<Defectlog> list = util.Facade.getDefectLogFacade().findAll();
            showLogList(out, list);
        } catch (Exception ex) {
            Controller.log.error("Error showAllLogs: " + ex.getMessage());
        }
           
    }
    
    public static void showSearchResult(JspWriter out, String title, String statusID, 
            String severityID, String priorityID, String logtypeID) {
        Controller.log.info("showSearchResult");
        try {
            DefectlogFacadeRemote facade = util.Facade.getDefectLogFacade();
            List<Defectlog> list = facade.search(title, statusID, severityID, priorityID, logtypeID);
            showLogList(out, list);
        } catch(Exception ex) {
            Controller.log.error("Error showSearchResult: " + ex.getMessage());
        }
    }

    /**
     * process requested action from client.
     */
    public static void processAction(HttpServletRequest request) {
        String action = request.getParameter("action");
        Controller.log.info("defectLogController.processAction");

        try {
            if (Constants.INSERT.equalsIgnoreCase(action)) {
                //Insert DefectLog into Database.
                insertDefectLog(request);

            } else if (Constants.EDIT.equalsIgnoreCase(action)) {
                //Edit DefectLog.
                editDefectLog(request);
            } else if (Constants.DELETE.equalsIgnoreCase(action)) {
                //Delete DefectLog from Database.
                deleteDefectLog(request);

            } else if (Constants.SEARCH.equalsIgnoreCase(action)) {
                //Get search result.
                searchLog(request);
                
            } else if (Constants.SHOW_EDIT_PAGE.equalsIgnoreCase(action)) {
                //Show edit page.
                showEditPage(request);
            } else if (Constants.SHOW_ALL.equalsIgnoreCase(action)) {
                //Show all logs in search page.
                unSearch(request);
            }

        } catch (Exception ex) {
            Controller.log.error("Error severityController.processAction: " + ex.getMessage());
        }
    }

    /**
     * Statistic DefectLogs.
     */
    public static void statistic(JspWriter out) {
        Controller.log.info("Log Statictis.");
        try {
            DefectlogFacadeRemote facade = util.Facade.getDefectLogFacade();
            List<Logtype> typeList = util.Facade.getLogTypeFacade().findAll();
            List<Employee> employeeList = util.Facade.getEmployeeFacade().findAll();
            List<Logstatus> statusList = util.Facade.getLogStatusFacade().findAll();
            List<Severity> severityList = util.Facade.getSeverityFacade().findAll();
            List<Priority> priorityList = util.Facade.getPriorityFacade().findAll();

            //Show total of logs.
            out.println("<h2 style='margin: 0px;'>Total Logs: " + facade.count() + "</h2></br>");
            out.print("<h2 style='margin: 0px;'>Detail:</h2></br>");

            //Show total by Status.
            out.println("<ul style='float: left; width: 15%; list-style: none;'><h3>By Status:</h3></br>");
            Logstatus statusTemp = null;
            for (int i = 0; i < statusList.size(); i++) {
                statusTemp = statusList.get(i);
                out.println("<li>" + statusTemp.getName() + ": " + facade.countByStatus(statusTemp)
                        + "</li>");
            }
            out.println("</ul>");

            //Show total by Type.
            out.println("<ul style='float: left; width: 15%; list-style: none;'><h3>By Type:</h3></br>");
            Logtype typeTemp = null;
            for (int i = 0; i < typeList.size(); i++) {
                typeTemp = typeList.get(i);
                out.println("<li>" + typeTemp.getName() + ": " + facade.countByLogType(typeTemp)
                        + "</li>");
            }
            out.println("</ul>");

            //Show total by Severity.
            out.println("<ul style='float: left; width: 15%; list-style: none;'><h3>By Severity:</h3></br>");
            Severity severityTemp = null;
            for (int i = 0; i < employeeList.size(); i++) {
                severityTemp = severityList.get(i);
                out.println("<li>" + severityTemp.getName() + ": " + facade.countBySeverity(severityTemp)
                        + "</li>");
            }
            out.println("</ul>");

            //Show total by Priority.
            out.println("<ul style='float: left; width: 15%; list-style: none;'><h3>By Priority:</h3></br>");
            Priority priorityTemp = null;
            for (int i = 0; i < employeeList.size(); i++) {
                priorityTemp = priorityList.get(i);
                out.println("<li>" + priorityTemp.getName() + ": " + facade.countByPriority(priorityTemp)
                        + "</li>");
            }
            out.println("</ul>");

            //Show total by Employee.
            out.println("<ul style='float: left; width: 15%; list-style: none;'><h3>By Author:</h3></br>");
            Employee employeeTemp = null;
            for (int i = 0; i < employeeList.size(); i++) {
                employeeTemp = employeeList.get(i);
                out.println("<li>" + employeeTemp.getShortName() + ": " + facade.countByEmployee(employeeTemp)
                        + "</li>");
            }
            out.println("</ul>");
            out.println("<div class='clear'></div>");
        } catch (Exception ex) {
            Controller.log.error("Error showAllLog: " + ex.getMessage());
        }
    }

    /**
     * Delete a log from database.
     */
    public static void deleteDefectLog(HttpServletRequest request) throws Exception {
        Controller.log.info("deleteDefectLog");
        String selectedID = request.getParameter("selectedItemID");
        if ((selectedID == null) || "".equals(selectedID)) {
            throw new Exception("The input ID is null");
        } else {
            int id = Integer.parseInt(selectedID);
            util.Facade.getDefectLogFacade().deleteByID(id);

            Controller.sendMessage(request, "Deleted succefully.", false);
            Controller.log.info("deleteDefectLog Successfully.");
        }
    }
    
    public static Defectlog getInfoToLogObject(HttpServletRequest request, Defectlog defect) {
        Controller.log.info("getInfoToLogObject");
        try {

            /*
             * Declare variables.
             */
            String title, stringCreateDate, description, product, corrective;
            java.sql.Date createDate;
            Logstatus status;
            Severity severity;
            Logtype logType;
            Employee defectBy, assignTo, fixedBy;
            Priority priority;
            Project project;

            /*
             * Get values from HttpServletRequest.
             */
            title = request.getParameter("txtTitle");
            Controller.log.info("title=" + title);
            if ((title == null) || ("".equals(title))) {
                Controller.sendMessage(request, "Error: Log title is not set.", true);
                throw new Exception("Error: Log title is not set.");
            }

            description = request.getParameter("txtDescription");
            Controller.log.info("description=" + description);
            if ((description == null) || ("".equals(description))) {
                Controller.sendMessage(request, "Error: Log description is not set.", true);
                throw new Exception("Error: Log description is not set.");
            }

//            stringCreateDate = request.getParameter("txtCreate");
//            String createDate_date = request.getParameter("txtCreate_date");
//            String createDate_month = request.getParameter("txtCreate_month");
//            String createDate_year = request.getParameter("txtCreate_year");
//            Controller.log.info("stringCreateDate=" + stringCreateDate);
//            if ((stringCreateDate == null) || ("".equals(stringCreateDate))) {
//                Controller.sendMessage(request, "Error: Created Date is not set.", true);
//                throw new Exception("Error: Created Date is not set.");
//            }

            product = request.getParameter("txtProduct");
            Controller.log.info("product=" + product);
            corrective = request.getParameter("txtCorrective");
            Controller.log.info("corrective=" + corrective);

            createDate = util.StringDate.createDate(request, "txtCreate_date",
                    "txtCreate_month", "txtCreate_year");
            if (createDate == null) {
                Controller.sendMessage(request, "The given Created Date is incorrect.", true);
                Controller.log.error("Cannot get CreatedDate");
            } else {
                Controller.log.info("createdDate=" + createDate.toString());
            }

            /*
             * Get required beans.
             */
            //Project.
            ProjectFacadeRemote projectFacade = util.Facade.getProjectFacade();
            String projectID = request.getParameter("cbxProjectId");
            Controller.log.info("cbxProjectId=" + projectID);
            if ((projectID == null) || "none".equalsIgnoreCase(projectID)) {
                Controller.sendMessage(request, "Error: Project Name is not set.", true);
                throw new Exception("Error: Project Name is not set.");
            } else {
                project = projectFacade.find(projectID);
                project = projectFacade.merge(project);
            }

            //LogStatus.
            LogstatusFacadeRemote statusFacade = util.Facade.getLogStatusFacade();
            String statusID = request.getParameter("cbxStatus");
            Controller.log.info("cbxStatus=" + statusID);
            if ((statusID == null) || "none".equalsIgnoreCase(statusID)) {
                Controller.sendMessage(request, "Error: Log Status is not set.", true);
                throw new Exception("Error: Log Status is not set.");
            } else {
                status = statusFacade.find(statusID);
                status = statusFacade.merge(status);
            }

            //Severity.
            SeverityFacadeRemote severityFacade = util.Facade.getSeverityFacade();
            String severityID = request.getParameter("cbxSeverity");
            Controller.log.info("cbxSeverity=" + severityID);
            if ((severityID == null) || "none".equalsIgnoreCase(severityID)) {
                Controller.sendMessage(request, "Error: Severity is not set.", true);
                throw new Exception("Error: Severity is not set.");
            } else {
                severity = severityFacade.find(severityID);
                severity = severityFacade.merge(severity);
            }

            //LogType.
            LogtypeFacadeRemote logTypeFacade = util.Facade.getLogTypeFacade();
            String logTypeID = request.getParameter("cbxLogType");
            Controller.log.info("cbxLogType=" + logTypeID);
            if ((logTypeID == null) || "none".equalsIgnoreCase(logTypeID)) {
                Controller.sendMessage(request, "Error: Logtype is not set.", true);
                throw new Exception("Error: Logtype is not set.");
            } else {
                logType = logTypeFacade.find(logTypeID);
                logType = logTypeFacade.merge(logType);
            }

            //Priority.
            PriorityFacadeRemote PriorityFacade = util.Facade.getPriorityFacade();
            String priorityID = request.getParameter("cbxPriority");
            Controller.log.info("cbxPriority=" + priorityID);
            if ((priorityID == null) || "none".equalsIgnoreCase(priorityID)) {
                Controller.sendMessage(request, "Error: Priority is not set.", true);
                throw new Exception("Error: Priority is not set.");
            } else {
                priority = PriorityFacade.find(priorityID);
                priority = PriorityFacade.merge(priority);
            }

            //Employees.
            EmployeeFacadeRemote employeeFacade = util.Facade.getEmployeeFacade();
            String defectByID = request.getParameter("cbxDefectBy");
            String assignToID = request.getParameter("cbxAssignTo");
            String fixedByID = request.getParameter("cbxFixedBy");
            Controller.log.info("cbxDefectBy=" + request.getParameter("cbxDefectBy"));
            Controller.log.info("cbxAssignto=" + request.getParameter("cbxAssignTo"));
            Controller.log.info("cbxFixedBy=" + request.getParameter("cbxFixedBy"));
            if ((defectByID == null) || "none".equalsIgnoreCase(defectByID)) {
                Controller.sendMessage(request, "Error: Defected By is not set.", true);
                throw new Exception("Error: Project Name is not set.");
            } else {
                defectBy = employeeFacade.find(Integer.parseInt(defectByID));
                defectBy = employeeFacade.merge(defectBy);
            }
            if ((assignToID == null) || "none".equalsIgnoreCase(assignToID)) {
                assignTo = null;
            } else {
                assignTo = employeeFacade.find(Integer.parseInt(assignToID));
                assignTo = employeeFacade.merge(assignTo);
            }
            if ((fixedByID == null) || "none".equalsIgnoreCase(fixedByID)) {
                fixedBy = null;
            } else {
                fixedBy = employeeFacade.find(Integer.parseInt(fixedByID));
                fixedBy = employeeFacade.merge(fixedBy);
            }

            //Dates.
            java.sql.Date deadline = null, fixedDate = null, closedDate = null;
            deadline = util.StringDate.createDate(request, "txtDeadline_date",
                    "txtDeadline_month", "txtDeadline_year");
            fixedDate = util.StringDate.createDate(request, "txtFixedDate_date",
                    "txtFixedDate_month", "txtFixedDate_year");
            closedDate = util.StringDate.createDate(request, "txtClosedDate_date",
                    "txtClosedDate_month", "txtClosedDate_year");
//            String strDeadline = request.getParameter("txtDeadline");
//            String strFixedDate = request.getParameter("txtFixedDate");
//            String strClosedDate = request.getParameter("txtClosedDate");
//            if ((strDeadline != null) && !("".equals(strDeadline))) {
//                deadline = new java.sql.Date(new java.util.Date(request.getParameter("txtDeadline")).getTime());
//            }
//            if ((strFixedDate != null) && !("".equals(strFixedDate))) {
//                fixedDate = new java.sql.Date(new java.util.Date(request.getParameter("txtFixedDate")).getTime());
//            }
//            if ((strClosedDate != null) && !("".equals(strClosedDate))) {
//                closedDate = new java.sql.Date(new java.util.Date(request.getParameter("txtClosedDate")).getTime());
//            }

            //Re-format to unicode.
            title = util.Unicode.changeToUnicode(title);
            description = util.Unicode.changeToUnicode(description);

            /*
             * Do check validation and insert into database.
             */
            defect.setTitle(title);
            defect.setDescription(description);
            defect.setAssignedTo(assignTo);
            defect.setDefectedBy(defectBy);
            defect.setFixedBy(fixedBy);
            defect.setLogTypeID(logType);
            defect.setClosedDate(closedDate);
            defect.setDeadline(deadline);
            defect.setFixedDate(fixedDate);
            defect.setProjectID(project);
            defect.setStatusID(status);
            defect.setProduct(product);
            defect.setSeverityID(severity);
            defect.setCreatedDate(createDate);
            defect.setCorrectiveAction(corrective);
            defect.setPriorityID(priority);

            Controller.log.info("getInfoToLogObject End.");

        } catch (Exception ex) {
            Controller.log.error("error insertDefectLog: " + ex.getMessage());
        }
        
        return defect;
    }
    
    public static void editDefectLog(HttpServletRequest request) {
        Controller.log.info("editDefectLog");
        try {
            String strID = request.getParameter("selectedItemID");
            if(strID==null || strID.isEmpty()) {
                Controller.log.error("The selected ID is null");
                throw new Exception("The selected ID is null");
            } else {
                int id = Integer.parseInt(strID);
                DefectlogFacadeRemote facade = util.Facade.getDefectLogFacade();
                Defectlog defect = facade.find(id);
                
                defect = getInfoToLogObject(request, defect);
                facade.edit(defect);
                
                Controller.sendMessage(request, "Edit Successfully.", false);
                Controller.log.info("editDefectlog End.");
            }
            
        } catch (Exception ex) {
            Controller.log.error("Error editDefectLog: " + ex.getMessage());
        }
    }

    /**
     * Do insert a defect log into database.
     */
    public static void insertDefectLog(HttpServletRequest request) {
        Controller.log.info("insertDefectLog");
        try {
            /*
             * Do check validation and insert into database.
             */
            DefectlogFacadeRemote server = util.Facade.getDefectLogFacade();
            Controller.log.info("defectLog MaxID: " + server.getMaxID());
            Defectlog defect = new Defectlog(server.getMaxID() + 1);
            defect = getInfoToLogObject(request, defect);
            server.insert(defect);

            Controller.sendMessage(request, "Insert Successfully.", false);
            Controller.log.info("Insert Defectlog End.");

        } catch (Exception ex) {
            Controller.log.error("error insertDefectLog: " + ex.getMessage());
        }
    }

    /**
     * Show the edit log page.
     */
    public static void showEditPage(HttpServletRequest request) throws Exception {
        controller.Controller.log.info("Begin showEditPage");
        String selectedID = request.getParameter("selectedItemID");
        if ((selectedID == null) || "".equals(selectedID)) {
            Controller.log.error("The selected ID is null");
            throw new Exception("The selected ID is null");
        } else {
            HttpSession session = request.getSession();
            int id = Integer.parseInt(selectedID);
            Defectlog log = util.Facade.getDefectLogFacade().find(id);
            if (log != null) {
                Controller.log.info("DefectLog found.");
                Date createDate = log.getCreatedDate();
                Date deadline = log.getDeadline();
                Date fixedDate = log.getFixedDate();
                Date closedDate = log.getClosedDate();
                Employee assignedTo = log.getAssignedTo();
                Employee fixedBy = log.getFixedBy();
                
                session.setAttribute("selectedItemID", log.getLogID().toString());
                session.setAttribute("defectLogID", log.getLogID().toString());
                session.setAttribute("title", log.getTitle());
                session.setAttribute("description", log.getDescription());
                session.setAttribute("product", log.getProduct());
                session.setAttribute("correctiveAction", log.getCorrectiveAction());
                session.setAttribute("projectID", log.getProjectID().getProjectID());
                session.setAttribute("priorityID", log.getPriorityID().getPriorityID());
                session.setAttribute("severityID", log.getSeverityID().getSeverityID());
                session.setAttribute("statusID", log.getStatusID().getLogStatusID());
                session.setAttribute("typeID", log.getLogTypeID().getLogTypeID());
                session.setAttribute("defectedByID", log.getDefectedBy().getEmployeeID().toString());
                session.setAttribute("createdDate_date", Integer.toString(createDate.getDate()));
                session.setAttribute("createdDate_month", Integer.toString(createDate.getMonth() + 1));
                session.setAttribute("createdDate_year", Integer.toString(createDate.getYear() + 1900));

                if (assignedTo != null) {
                    session.setAttribute("assignedToID", assignedTo.getEmployeeID().toString());
                }

                if (fixedBy != null) {
                    session.setAttribute("fixedByID", fixedBy.getEmployeeID().toString());
                }

                if (deadline != null) {
                    session.setAttribute("deadline_date", Integer.toString(deadline.getDate()));
                    session.setAttribute("deadline_month", Integer.toString(deadline.getMonth() + 1));
                    session.setAttribute("deadline_year", Integer.toString(deadline.getYear() + 1900));
                }

                if (fixedDate != null) {
                    session.setAttribute("fixedDate_date", Integer.toString(fixedDate.getDate()));
                    session.setAttribute("fixedDate_month", Integer.toString(fixedDate.getMonth() + 1));
                    session.setAttribute("fixedDate_year", Integer.toString(fixedDate.getYear() + 1900));
                }

                if (closedDate != null) {
                    session.setAttribute("closedDate_date", Integer.toString(closedDate.getDate()));
                    session.setAttribute("closedDate_month", Integer.toString(closedDate.getMonth() + 1));
                    session.setAttribute("closedDate_year", Integer.toString(closedDate.getYear() + 1900));
                }
                Controller.log.info("Set session finish.");
            } else {
                Controller.log.error("DefectLog not found.");
                throw new Exception("The selected log is not found");
            }
        }
    }

    /**
     * Search Log.
     */
    public static void searchLog(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String title_search = request.getParameter("txtTitle");
        String status_search = request.getParameter("cbxStatus");
        String severity_search = request.getParameter("cbxSeverity");
        String priority_search = request.getParameter("cbxPriority");
        String logtype_search = request.getParameter("cbxLogType");
        if(status_search == null || "none".equalsIgnoreCase(status_search)) status_search = "";
        if(severity_search==null || "none".equalsIgnoreCase(severity_search)) severity_search = "";
        if(priority_search==null || "none".equalsIgnoreCase(priority_search)) priority_search = "";
        if(logtype_search==null || "none".equalsIgnoreCase(logtype_search)) logtype_search = "";
        
        session.setAttribute("title_search", title_search);
        session.setAttribute("statusID_search", status_search);
        session.setAttribute("severityID_search", severity_search);
        session.setAttribute("priorityID_search", priority_search);
        session.setAttribute("logtypeID_search", logtype_search);
        controller.Controller.log.info("title_search: " + session.getAttribute("title_search"));
        controller.Controller.log.info("statusID_search: " + session.getAttribute("statusID_search"));
        controller.Controller.log.info("severityID_search: " + session.getAttribute("severityID_search"));
        controller.Controller.log.info("priorityID_search: " + session.getAttribute("priorityID_search"));
        controller.Controller.log.info("logtypeID_search: " + session.getAttribute("logtypeID_search"));
    }
    
    public static void unSearch(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("title_search");
        session.removeAttribute("statusID_search");
        session.removeAttribute("severityID_search");
        session.removeAttribute("priorityID_search");
        session.removeAttribute("logtypeID_search");
    }
}
